from flask import Blueprint, render_template, g, redirect, request
from app import db
from app.models import Product, User, Updatejour, Updateturn
import time

index_page = Blueprint('index_page', __name__, template_folder='templates')
@index_page.route('/index',methods = ['GET','POST'])
def index():
    """
    server_lists=server_lists, pro_num=服务器数量, user_num=使用人数,
                           hs_current_user=hs_current_user, mes_lists=mes_lists, mes_len=mes_len,
                           up_times=升级次数（当日）, use_time_avg=平均升级时间
    :return:
    """
    if g.user is not None and g.user.is_authenticated:
        current_date = str(time.strftime('%Y.%m.%d', time.localtime(time.time())))
        use_time_sum = 0
        update_lists = db.session.query(Updateturn.use_time).filter_by(begin_date = current_date,up_status=2).all()
        up_times = len(update_lists)
        if up_times == 0:
            use_time_avg = 0
        else:
            for ti in update_lists:
                use_time_sum = use_time_sum+ti[0]
            use_time_avg = round(use_time_sum/up_times,2)

        server_lists = db.session.query(Product.server_name,Product.server_type,Product.server_address,Product.server_port,Product.creat_date,Product.creat_person,Product.group).filter().all()
        pro_num = len(server_lists)
        user_num = len(db.session.query(User).filter().all())
        hs_current_id = str(g.user).replace("'", "")
        hs_current_user = db.session.query(User.username).filter_by(id = hs_current_id).first()[0]
        mes_lists = db.session.query(Updatejour.output,Updatejour.update_date,Updatejour.update_time,Updatejour.message,Updatejour.id,Updatejour.log_path).filter_by(read_status = 1,up_persion=hs_current_user).all()
        mes_len = len(mes_lists)
        if request.method == 'POST':
            if request.values.get('fun')=='deletemes':
                de_id = request.values.get('mes_id')
                u = Updatejour.query.filter_by(id = de_id).first()
                u.read_status = 2
                db.session.add(u)
                db.session.commit()

    else:
        return redirect('/login')
    return render_template('hs-index.html', server_lists=server_lists, pro_num=pro_num, user_num=user_num,
                           hs_current_user=hs_current_user, mes_lists=mes_lists, mes_len=mes_len,
                           up_times=up_times, use_time_avg=use_time_avg)